package bg.btanev.eightyfour.gwtfacade.commandhandler;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.Validate;

import bg.btanev.eightyfour.domain.Tag;
import bg.btanev.eightyfour.domain.Target;
import bg.btanev.eightyfour.gwtfacade.converter.DtoConverter;
import bg.btanev.eightyfour.service.TargetService;
import bg.btanev.eightyfour.shared.command.CommandResult;
import bg.btanev.eightyfour.shared.command.target.FindTagsForTargetCommand;
import bg.btanev.eightyfour.shared.command.target.FindTagsForTargetInput;
import bg.btanev.eightyfour.shared.dto.TagDto;
import bg.btanev.eightyfour.shared.dto.TargetDto;

/**
 *
 * @author B.Tanev
 *
 */
public class FindTagsForTargetCommandHandler
		extends
		GenericCommandHandler<FindTagsForTargetInput, ArrayList<TagDto>, CommandResult<FindTagsForTargetInput, ArrayList<TagDto>>, FindTagsForTargetCommand> {

	private final TargetService targetService;
	private final DtoConverter converter;

	public FindTagsForTargetCommandHandler(TargetService targetService, DtoConverter converter) {
		super();

		Validate.notNull(targetService);
		Validate.notNull(converter);

		this.targetService = targetService;
		this.converter = converter;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected ArrayList<TagDto> doExecuteInternal(FindTagsForTargetInput attachedInput) {
		Validate.notNull(attachedInput);

		TargetDto targetInput = attachedInput.getTarget();
		Validate.notNull(targetInput);

		Long targetId = targetInput.getId();
		Validate.notNull(targetId);
		Validate.isTrue(targetId.longValue() > 0);

		ArrayList result = null;
		Target target = targetService.findByIdentifier(targetId);
		if (target != null) {
			List<Tag> tags = targetService.findTagsForTarget(target);
			result = converter.collectionDomainToDto(tags, 0);
		}

		return result;
	}

	@Override
	protected CommandResult<FindTagsForTargetInput, ArrayList<TagDto>> packCommandResult(FindTagsForTargetInput input,
			ArrayList<TagDto> detachedResult) {

		return new CommandResult<FindTagsForTargetInput, ArrayList<TagDto>>(input, detachedResult);
	}

	@Override
	public FindTagsForTargetInput attach(FindTagsForTargetInput input) {
		return input;
	}

	@Override
	public ArrayList<TagDto> detach(ArrayList<TagDto> result) {
		return result;
	}
}
